/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

.controller('QueueCtrl', ['$rootScope', '$scope', 'QueueService', function ($rootScope, $scope, QueueService) {

    //数据列表
    $scope.queue = [];

    $scope.loadData = function () {
        QueueService.list()
            .success(function (result) {
                if (result.success) {
                    $scope.queue = result.data || [];
                    angular.forEach($scope.queue, function (item) {
                        item.waybillStatusText = Tools.getDWaybillStatusText(item.waybillStatus);
                    });
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    };

    //取消排队
    $scope.removeQueue = function (orderCode) {
        QueueService.removeOrder({
            orderCodes: orderCode
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '取消排队成功',
                    timeOut: 3000
                });
                $scope.loadData();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    //订单置顶
    $scope.topQueue = function (orderCode) {
        QueueService.topOrder({
            orderCodes: orderCode
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '置顶成功',
                    timeOut: 3000
                });
                $scope.loadData();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 加载数据
    $scope.loadData();
}])

.controller('DriverQueueCtrl', ['$rootScope', '$scope', 'QueueService', function ($rootScope, $scope, QueueService) {

    $scope.driverQueue = [];

    $scope.loadDate = function () {
        QueueService.listDriver()
            .success(function (result) {
                if (result.success) {
                    $scope.driverQueue = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    };

    // 移除队列
    $scope.removeDriver = function (phone) {
        QueueService.removeDriver({
            phone: phone
        }).success(function (result) {
            if (result.success) {
                $rootScope.hycadmin.toast({
                    title: '移除司机队列成功',
                    timeOut: 3000
                });
                $scope.loadDate();
            } else {
                $rootScope.hycadmin.toast({
                    title: '移除司机异常',
                    timeOut: 3000
                });
            }
        });
    }

    $scope.loadDate();
}])
.controller('QuickDispatchListCtrl', ['$rootScope', '$scope', 'QuickDispatchService','$modal', function ($rootScope, $scope, QuickDispatchService,$modal){
        $scope.allDispatch = [];
        $scope.quickDispatch =[];
        $scope.normalDispatch =[];
        $scope.searchOrderCode = '';
        $scope.beginDateTime = '';  // 开始时间
        $scope.endDateTime = '';    //查询结束时间
        $scope.addCarriage = '';    //添加的运费
        $scope.requirements = '';   //特殊要求
        $scope.billId ='';      //运单id号
        $scope.transCode = '';
        function loadData(code,type){
            var  params ={};
            params['orderCode'] = code;
            params['waybillType'] = type;
            params['beginDate'] = $scope.beginDateTime;
            params['endDate'] = $scope.endDateTime;
            params['pageSize'] = 5;
            QuickDispatchService.listQuickDispatch(params)
                .success(function(result){
                    if( result.success){
                        if( type == '10'){
                            $scope.normalDispatch = result.data.dWaybillList;
                            $scope.userTruckObj.pageNo = result.data.page.pageNo;
                            $scope.userTruckObj.pageSize = result.data.page.pageSize;
                            $scope.page.totalPage = result.data.page.totalRecord;
                            $scope.buildPage();
                        } else if(type == '20'){
                            $scope.quickDispatch = result.data.dWaybillList;
                        }
                    } else {
                        $rootScope.hycadmin.toast({
                            title: "请求数据失败！",
                            // title: result.message,
                            timeOut: 3000
                        });
                    }
                })
        }
            // loadData('','10');
            loadData('','20');

        //    日期转化函数
        $scope.format = function(time, format ){
            var t = new Date(time);
            var tf = function(i){return (i < 10 ? '0' : '') + i};
            return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a){
                switch(a){
                    case 'yyyy':
                        return tf(t.getFullYear());
                        break;
                    case 'MM':
                        return tf(t.getMonth() + 1);
                        break;
                    case 'mm':
                        return tf(t.getMinutes());
                        break;
                    case 'dd':
                        return tf(t.getDate());
                        break;
                    case 'HH':
                        return tf(t.getHours());
                        break;
                    case 'ss':
                        return tf(t.getSeconds());
                        break;
                }
            })
        };
        //alert(format("Tue May 02 2017 00:00:00 GMT+0800 (中国标准时间)", 'yyyy-MM-dd HH:mm:ss'));

        // 账单状态码对应汉子转换
        $scope.changeCode = function(statusCode){
            switch(statusCode){
                case '-10':
                    return '废弃';
                    break;
                case '0':
                    return '未安排订单';
                    break;
                case '1':
                    return '已发布';
                    break;
                case '5':
                    return '待发车';
                    break;
                case '10':
                    return '在途';
                    break;
                case '20':
                    return '已交车';
                    break;
                case '30':
                    return '已完成';
                    break;
                case '40':
                    return '未回单';
                    break;
                case '90':
                    return '取消';
                    break;
                case '100':
                    return '派单失败';
                    break;
            }
        };

        //    查询
        $scope.search = function() {
            if ((+$scope.endDateTime) - (+$scope.beginDateTime) < 0) {
                $rootScope.hycadmin.toast({
                    title: '查询开始时间不能大于结束时间',
                    timeOut: 3000
                });
                return 0;
            } else {
                var  params ={};
                params['orderCode'] = $scope.searchOrderCode;
                params['waybillType'] = '10';
                params['beginDate'] = $scope.beginDateTime;
                params['endDate'] = $scope.endDateTime;
                params['pageSize'] = 5;
                QuickDispatchService.listQuickDispatch(params)
                    .success(function(result){
                        if( result.success){
                                $scope.normalDispatch = result.data.dWaybillList;
                                $scope.userTruckObj.pageNo = result.data.page.pageNo;
                                $scope.userTruckObj.pageSize = result.data.page.pageSize;
                                $scope.page.totalPage = result.data.page.totalRecord;
                                $scope.buildPage();
                                $scope.reset();
                        } else {
                            $rootScope.hycadmin.toast({
                                title: "请求数据失败！",
                                // title: result.message,
                                timeOut: 3000
                            });
                        }
                    })
            }
        };

        //重置
        $scope.reset = function(){
            $scope.searchOrderCode ='';
            $scope.beginDateTime = '';
            $scope.endDateTime = '';
            $('#addCarriage').val('');
            $('#requirements').val('');

        };
        $scope.resetT =function(){
            loadData('','10');
            $scope.searchOrderCode ='';
            $scope.beginDateTime = '';
            $scope.endDateTime = '';
        };
        // 设置模态窗口
        var myOtherModal = $modal({scope: $scope, title: '添加急发单条件', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/dialog/quick-dispatch-modal-view.html', show: false});
        $scope.showModal = function ($event) {
            $scope.billId = parseInt($($event.target).next().html());
            $scope.transCode = parseFloat($($event.target).siblings().eq(0).html()).toFixed(2);
            myOtherModal.$promise.then(myOtherModal.show); //显示弹框
        };

        //每当退出或确定时，都要清空弹框内容
        $scope.clearQuick = function(){
            $scope.addCarriage = '';
            $scope.requirements = '';
        };

        //普通单 --> 急发单
        $scope.updateQuick = function(){
            $scope.addCarriage = $('#addCarriage').val();
            $scope.requirements= $('#requirements').val();
            if( $scope.addCarriage && $scope.requirements ){
            //    提交数据
                var  params ={};
                params['orderId'] = $scope.billId;
                params['waybillType'] = Number(20);
                params['extraCost'] = Number($scope.addCarriage);
                params['specialRequired'] = $scope.requirements;
                QuickDispatchService.markQuickDispatchUp(params)
                    .success(function(result){
                        if( result.success){
                            //刷新表格
                            loadData('','20');
                            loadData('','10')
                        } else {
                            $rootScope.hycadmin.toast({
                                title: "请求数据失败！",
                                // title: result.message,
                                timeOut: 3000
                            });
                        }
                    });
                myOtherModal.$promise.then(myOtherModal.hide); //隐藏弹框
                $scope.reset();  // 搜索加急时，清空搜索栏
            }  else {
                $rootScope.hycadmin.toast({
                    title: '增加运费或特殊要求还没填！',
                    timeOut: 3000
                });
            }

        };

        //急发单 --> 普通单
        $scope.updateNormal = function( $event ){
            var  params ={};
            params['orderId'] = parseInt($($event.target).next().html());
            params['waybillType'] = '10';
            params['extraCost'] = parseInt($($event.target).siblings().eq(9).html())| null;
            params['specialRequired'] = $($event.target).siblings().eq(10).html() | null;
            QuickDispatchService.markQuickDispatchUp(params)
                .success(function(result){
                    if( result.success){
                        //刷新表格
                        loadData('','20');
                        loadData('','10')
                    } else {
                        $rootScope.hycadmin.toast({
                            title: "请求数据失败！",
                            // title: result.message,
                            timeOut: 3000
                        });
                    }
                });
        };

    //    分页模块
        $scope.page = {
            pageNo:1,
            totalPage : 10
        };
        $scope.pageScd = {
            pageNo:1,
            totalPage : 10
        };

        // 当前对象(第一个)
        $scope.userTruckObj = {
            pageNo: 1, //激活时的页码
            pageSize: 5,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.page.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.page.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData('10');
            }
        };
        $scope.userTruckObjScd = {
            pageNo: 1, //激活时的页码
            pageSize: 5,
            loadMore: function ($event, pageNo) {
                this.pageNo = pageNo;
                if ((this.pageNo > $scope.pageScd.totalPage)) {
                    $event.stopPropagation();
                    this.pageNo = $scope.pageScd.totalPage;
                    return;
                } else if (this.pageNo < 1) {
                    $event.stopPropagation();
                    this.pageNo = 1;
                    return;
                }
                $scope.loadData('20');
            }
        };

        // 初始化数据列表
        $scope.loadData = function( type) {
            QuickDispatchService.listQuickDispatch({
                pageNo:   type == '10' ? $scope.userTruckObj.pageNo : $scope.userTruckObjScd.pageNo,       //当前激活页码
                pageSize: type == '10' ? $scope.userTruckObj.pageSize : $scope.userTruckObjScd.pageSize,   //获取页码的数量
                orderCode : '',
                waybillType : type,
                beginDate : $scope.beginDateTime,
                endDate : $scope.endDateTime
            }).success(function (result) {
                if (result.success) {
                    if( type =='10'){
                        $scope.normalDispatch = result.data.dWaybillList;
                        $scope.userTruckObj.pageNo = result.data.page.pageNo;
                        $scope.userTruckObj.pageSize = result.data.page.pageSize;
                        $scope.page = result.data.page;
                        $scope.buildPage();
                        $scope.reset();
                    }   else if( type == '20'){
                        $scope.quickDispatch = result.data.dWaybillList;
                        $scope.userTruckObjScd.pageNo = result.data.page.pageNo;
                        $scope.userTruckObjScd.pageSize = result.data.page.pageSize;
                        $scope.pageScd = result.data.page;
                        $scope.buildPageScd();
                        $scope.reset();
                    }
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        };
        $scope.buildPage=function(){
            $scope.item = [];
            var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
            var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
            for(var i=start; i <= end; i++){
                $scope.item.push(i);
            }
        };
        $scope.buildPageScd=function(){
            $scope.itemScd = [];
            var end = ($scope.pageScd.totalPage - $scope.userTruckObjScd.pageNo) > 5?($scope.userTruckObjScd.pageNo == 1?(parseInt($scope.userTruckObjScd.pageNo)+5):(parseInt($scope.userTruckObjScd.pageNo)+5)):$scope.pageScd.totalPage;
            var start = $scope.userTruckObjScd.pageNo > 5?($scope.userTruckObjScd.pageNo == 1?(parseInt($scope.userTruckObjScd.pageNo)-5):(parseInt($scope.userTruckObjScd.pageNo)-5)):1;
            for(var i=start; i <= end; i++){
                $scope.itemScd.push(i);
            }
        };
        $scope.loadData('10');
        $scope.loadData('20');

}])
.controller('QueueDriverCtrl', ['$rootScope', '$scope', '$state', 'QueueDriverService', function ($rootScope, $scope, $state, QueueDriverService) {
    $scope.driverList = [];
    $scope.driverInfo = {
        name: '',
        phone: ''
    };

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        QueueDriverService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            name: $scope.driverInfo.name,
            phone: $scope.driverInfo.phone
        }).success(function (result) {
            if (result.success) {
                $scope.driverList = result.data.list;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.driverInfo = {
            name: '',
            phone: ''
        };
        $scope.loadData('query');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    $scope.exportsQueueDriver = function () {
        //QueueDriverService.exportExecl({
        //    name: $scope.driverInfo.name,
        //    phone: $scope.driverInfo.phone
        //}).success(function (result) {
        //
        //});
        var url = 'tmsqueue/exportExecl';
        window.location.href = $rootScope.Context.path + '/download/exportExcel?host=tmsdriverHost&url=' + url + '&name=' + $scope.driverInfo.name + "&phone=" + $scope.driverInfo.phone;
        //$state.go('download/exportExcel', {url: '/tmsqueue/exportExecl', name: $scope.driverInfo.name, phone: $scope.driverInfo.phone});
    };

    $scope.loadData('load');

}]);